﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;
using LibraryMusicStore;
using MvcMusicStore.Infrastructure.Config;

namespace MvcMusicStore.Controllers
{
    [Authorize]
    public class CheckoutController : Controller
    {
        MusicStoreEntities storeDB = new MusicStoreEntities();
        public IRepository Repository { get; set; }
        const string PromoCode = "Free";

        //
        // GET: /Checkout/AddressAndPayment

        public ActionResult AddressAndPayment()
        {
            try
            {
                var cart = ShoppingCart.GetCart(this.HttpContext);
                if (cart.GetCount() == 0) return View("NoItems");

                Repository = new Repository();
                ViewData["User"] = Repository.FindUserByID(Convert.ToInt32(User.Identity.Name));

                return View();
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            try
            {
                var order = new Order();
                TryUpdateModel(order);

                Repository = new Repository();
                var user = Repository.FindUserByID(Convert.ToInt32(User.Identity.Name));

                user.address = order.Address;
                user.city = order.City;
                user.country = order.Country;
                user.email = order.Email;
                user.phone = order.Phone;
                user.fullname = order.FullName;

                Repository.CommitChanges();

                if (string.Equals(values["PromoCode"], PromoCode,
                   StringComparison.OrdinalIgnoreCase) == true)
                {
                    return View(order);
                }
                else
                {
                    order.Username = user.username;
                    order.OrderDate = DateTime.Now;

                    //get order total
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    var vat = storeDB.VATs.First(v => v.VATId == 1);
                    order.Total = cart.GetTotal() * (1 + storeDB.VATs.First().Value / 100);

                    //save order
                    storeDB.Orders.InsertOnSubmit(order);
                    storeDB.SubmitChanges();

                    //process the order 

                    cart.CreateOrder(order);

                    return RedirectToAction("Complete",
                        new { id = order.OrderId });
                }
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        //
        //Get: /Checkout/Compete
        public ActionResult Complete(int id)
        {
            try
            {
                //validate customer owns this order
                bool idValid = storeDB.Orders.Any(
                    o => o.OrderId == id &&
                        o.Username == ((EnhancedPrincipal)User).Data.username);

                if (idValid)
                {
                    return View(id);
                }
                return View("../Shared/Error");
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
            
        }
    }
}
